from tools.hash import verify_password
from fastapi import HTTPException
from tools.jwt_token import create_jwt
from models.user import User
from datetime import datetime
import requests

async def user_login(user: str, password: str) -> dict:
    if len(user) < 6 or len(password) < 6:
        raise HTTPException(status_code=403, detail="账号或密码长度不符合格式")
    else:
        user_object = await User.get_or_none(user=user)
        if not user_object or user_object.level < 4:
            raise HTTPException(status_code=403, detail="账号不存在")
        else:
            login_state = await verify_password(password, user_object.hash_password)
            if not login_state:
                raise HTTPException(status_code=403, detail="密码错误")
            else:
                # 更新最后登录时间为当前时间戳
                user_object.last_login = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

                await user_object.save(update_fields=["last_login"])  # 确保更改被保存到数据库
                token = await create_jwt({"sub": user_object.id, "lv": user_object.level})
                print(f"登录鉴权成功,\n登录用户{user_object.name},权限等级{user_object.level}\ntoken:{token}\ntime:{user_object.last_login}")
                return {"msg": "登录成功",
                        "access_token": token,
                        "name": user_object.name,
                        "role": user_object.role,
                        "login_time": user_object.last_login,
                        "from": user_object.from_place,
                        }